package com.hundsun.cprs.yyt.web.action.plate;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.hundsun.cprs.yyt.common.enums.EnumAreaCode;
import com.hundsun.cprs.yyt.common.enums.EnumBusinessCode;
import com.hundsun.cprs.yyt.common.enums.EnumCommonCode;
import com.hundsun.cprs.yyt.common.exception.ServiceCodeException;
import com.hundsun.cprs.yyt.common.exception.ServiceException;
import com.hundsun.cprs.yyt.common.fileUpload.FileUploadUtil;
import com.hundsun.cprs.yyt.common.redis.BaseRedisDao;
import com.hundsun.cprs.yyt.response.BaseResponse;
import com.hundsun.cprs.yyt.service.form.domain.FormAttrValues;
import com.hundsun.cprs.yyt.service.form.dto.FormInfo;
import com.hundsun.cprs.yyt.service.form.enums.EnumFormAttrMeta;
import com.hundsun.cprs.yyt.service.form.service.FormFacadeService;
import com.hundsun.cprs.yyt.service.goods.domain.query.GoodsQuery;
import com.hundsun.cprs.yyt.service.goods.service.GoodsService;
import com.hundsun.cprs.yyt.service.plate.domain.Plate;
import com.hundsun.cprs.yyt.service.plate.domain.PlateImage;
import com.hundsun.cprs.yyt.service.plate.domain.PlateInfo;
import com.hundsun.cprs.yyt.service.plate.domain.query.PlateQuery;
import com.hundsun.cprs.yyt.service.plate.service.PlateImageService;
import com.hundsun.cprs.yyt.service.plate.service.PlateService;
import com.hundsun.cprs.yyt.util.StringUtil;
import com.hundsun.cprs.yyt.util.UploadUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hundsun.cprs.yyt.web.action.BaseAction;
import com.hundsun.cprs.yyt.web.vo.JsonModel;
import com.hundsun.network.eclp.ex.common.PermissionEnum;
import com.hundsun.network.eclp.ex.security.AdminAccess;


@Controller
public class PlateAction extends BaseAction{
	@Autowired
	private PlateService plateService;
	@Autowired
	private PlateImageService plateImageService;
	@Autowired
	private BaseRedisDao<Plate> baseRedisDao;
	@Resource(name = "imageUploadUtil")
	private FileUploadUtil fileUploadUtil;
	@Autowired
	private FormFacadeService formFacadeService;
	@Autowired
	private GoodsService goodsService;

	@AdminAccess(PermissionEnum.PLATE_MANAGE_DEFEND)
	@RequestMapping(value = "plate/list.htm")
	public void list(@ModelAttribute("query") PlateQuery query, ModelMap model) {
	    //分页显示每页10条
		query.setPageSize(10);
		plateService.selectPlateByPage(query);
		model.addAttribute("EnumAreaCode",EnumAreaCode.toMap());
	}
	
	@AdminAccess(PermissionEnum.PLATE_MANAGE_ADD)
	@RequestMapping(value = "plate/add.htm", method = RequestMethod.GET)
	public void add(ModelMap model) {
		/*FormInfo form = formFacadeService.getFormInfoByCode(PlateService.DYNAMIC_FORM_CODE);
		if (form != null) {
		    form.render();
	        model.put("form", form);
        }*/
	}
	
	@AdminAccess(PermissionEnum.PLATE_MANAGE_ADD)
	@RequestMapping(value = "/plate/add", method = RequestMethod.POST)
	@ResponseBody
	public JsonModel add(@RequestBody Map<String,String> requestMap,HttpServletRequest request) throws Exception {
		try {
		    //获得固定属性
		    PlateInfo plate = JSON.parseObject(JSON.toJSONString(requestMap), PlateInfo.class);
		    //获得动态属性
		    /*FormInfo form = formFacadeService.getFormInfoByCode(PlateService.DYNAMIC_FORM_CODE);
		    if (form != null) {
		        List<FormAttrValues> formAttrValueList = form.loadValues(requestMap);
	            plate.setFormAttrValueList(formAttrValueList);
            }*/
		    //表单校验
			validateParam(plate);
			plateService.createPlate(plate);
			return new JsonModel(JsonModel.RESULD_CODE_SUCCESS,"专场新增成功");
		} catch (Exception e) {
			log.error("专场新增异常:",e);
			return new JsonModel(JsonModel.RESULD_CODE_FAIL,e.getMessage());
		}
	}

	/**
	 * 详情查看
	 * 
	 * */
	 @AdminAccess(PermissionEnum.PLATE_MANAGE_DEFEND_VIEW)
	 @RequestMapping("/plate/view.htm")
	 public String view(ModelMap model,@RequestParam(value="plateId") Long plateId) throws Exception {
        try {
            PlateInfo plate = plateService.selectPlateInfoById(plateId);
            model.put("plateInfo", plate);
            // 获得动态属性
            /*FormInfo form = formFacadeService.getFormInfoByCode(PlateService.DYNAMIC_FORM_CODE);
            if (form != null) {
                form.loadValues(plate.getFormAttrValueList());
                form.render();
                model.put("form", form);
            }*/
        } catch (ServiceCodeException e) {
            model.put("message", e.getMessage());
            return "error";
        } catch (Exception e) {
            log.error("查看专场信息失败", e);
        }
        return "plate/view";
	 }

	@AdminAccess(PermissionEnum.PLATE_MANAGE_DEFEND_UPDATE)
	@RequestMapping(value = "plate/edit.htm", method = RequestMethod.GET)
	public void edit(ModelMap model,@RequestParam(value="plateId") Long plateId) {
		try{
			PlateInfo plateInfo = plateService.selectPlateInfoById(plateId);
			model.put("plateInfo", plateInfo);
			
			/*FormInfo form = formFacadeService.getFormInfoByCode(PlateService.DYNAMIC_FORM_CODE);
			if (form != null) {
			    form.loadValues(plateInfo.getFormAttrValueList());
	            form.render();
	            model.put("form", form);
            }*/
		}catch (Exception e){
			log.error(EnumCommonCode.COMMON_BUSINESS_ERROR.getClass() + "，取得专场信息出错", e);
			throw new ServiceCodeException(EnumCommonCode.COMMON_BUSINESS_ERROR.getErrorNo(),
					EnumCommonCode.COMMON_BUSINESS_ERROR.getClass() + "，取得专场信息出错");
		}
	}

	@AdminAccess(PermissionEnum.PLATE_MANAGE_DEFEND_UPDATE)
	@RequestMapping(value = "/plate/edit", method = RequestMethod.POST)
	@ResponseBody
	public JsonModel platesEdit(@RequestBody Map<String,String> requestMap,HttpServletRequest request) throws Exception {
        //获得固定属性
        PlateInfo plateInfo = JSON.parseObject(JSON.toJSONString(requestMap), PlateInfo.class);
        //获得动态属性
        /*FormInfo form = formFacadeService.getFormInfoByCode(PlateService.DYNAMIC_FORM_CODE);
        if ( form != null) {
            form.setObjectId(plateInfo.getId());
            List<FormAttrValues> formAttrValueList = form.loadValues(requestMap);
            plateInfo.setFormAttrValueList(formAttrValueList);
        }*/
		try{
		    this.validateParam(plateInfo);
			//更新板块
			plateService.update(plateInfo);
			return new JsonModel(JsonModel.RESULD_CODE_SUCCESS,"专场修改成功");
		}catch (Exception e){
			return new JsonModel(JsonModel.RESULD_CODE_FAIL,e.getMessage());
		}
	}

	/**
	 * 异步删除专场
	 * 
	 * */
	@AdminAccess(PermissionEnum.PLATE_MANAGE_DEFEND_DELETE)
	@RequestMapping(value = "/plate/delete.json",method = RequestMethod.POST)
	public @ResponseBody BaseResponse deleteById(Long id) {
		BaseResponse resultResponse = new BaseResponse();
		resultResponse.setSuccess(true);
		try {
			plateService.deletePlate(id);
		} catch (ServiceCodeException sce) {
			resultResponse.setSuccess(false);
			resultResponse.setErrorNo(sce.getErrorCode());
			resultResponse.setErrorDesc(sce.getErrorDesc());
		} catch (ServiceException sce) {
		    resultResponse.setSuccess(false);
		    resultResponse.setErrorNo(1);
            resultResponse.setErrorDesc(sce.getMessage());
		} catch (Exception e) {
		    log.error("专场删除失败:",e);
		    resultResponse.setSuccess(false);
		    resultResponse.setErrorNo(1);
            resultResponse.setErrorDesc(e.getMessage());
		}
		return resultResponse;
	} 
	/*
	 * 异步删除专场的某个图片
	 * 
	 * */
	@RequestMapping(value = "/ajax/plate/image/delete.htm")
	public void deleteImage(@RequestParam("plateId") String plateId,@RequestParam("id") String id,ModelMap model, HttpServletResponse response) throws IOException{
		JSONObject json = new JSONObject();
		List<PlateImage> ImageList=plateImageService.selectPlateImageList(Long.parseLong(plateId));
		if( ImageList!=null){
			if(ImageList.size()>1){
				PlateImage plateImage = new PlateImage();
				plateImage.setId(Long.parseLong(id));
				plateImageService.delete(plateImage);
				List<PlateImage> plateImageList=plateImageService.selectPlateImageList(Long.parseLong(plateId));
				json.put("data", plateImageList);	
				json.put("info", "Yes");
			}else{
				json.put("data", ImageList);
				json.put("info", "No");
			}
		}
		try {
			response.getWriter().print(json);
		} catch (Exception e) {
			log.error(e, e);
		}
	}
	/*
	 * 异步校验专场排序号是否重复
	 * 
	 * */
	@RequestMapping("/plate/ajax/validateSort")
	public void getClassify(ModelMap model,@RequestParam(value = "code", required = true) String code,HttpServletResponse response){
		JSONObject json = new JSONObject();
		if (code != null) {
			//判断库里是否有相同的code
			List<Plate> plateList=plateService.selectPlateBySort(Long.parseLong(code));
			if(plateList.isEmpty()){
				json.put("data", "Y");
			}else{
				json.put("data", "N");
			}
		}
		try {
			response.getWriter().print(json);
		} catch (Exception e) {
			log.error(e, e);
		}
	}
	/*
	 * 异步校验专场编码是否重复
	 * 
	 * */
	@RequestMapping("/plate/ajax/validateCode.htm")
	public void getCode(ModelMap model,@RequestParam(value = "code", required = true) String code,HttpServletResponse response){
		JSONObject json = new JSONObject();
		if (code != null) {
			//判断库里是否有相同的code
			List<Plate> plateList=plateService.selectPlateByCode(code);
			if(plateList.isEmpty()){
				json.put("data", "Y");
			}else{
				json.put("data", "N");
			}
		}
		try {
			response.getWriter().print(json);
		} catch (Exception e) {
			log.error(e, e);
		}
	}
	/*
	 * 异步校验专场是否上传图片
	 * 
	 * */
	@RequestMapping("/plate/ajax/validateImage.htm")
	public void validateImage(ModelMap model,@RequestParam(value = "plateId", required = true) String plateId,HttpServletResponse response) throws Exception{
		JSONObject json = new JSONObject();
		if (plateId != null) {
			Long id=Long.parseLong(plateId);
			Plate plateImages = new Plate();
			plateImages = baseRedisDao.getValueByKey("plate:plate_"+id+"_img");
			//List<PlateImage> plateImageList=plateImageService.selectPlateImageList(id);
			if(null == plateImages) {
				json.put("data", "logoN");
			}else{
				json.put("data", "success");
			}
		}
		try {
			response.getWriter().print(json);
		} catch (Exception e) {
			log.error(e, e);
		}
	}
	
	@RequestMapping(value = "/plate/upload_image", method = RequestMethod.POST)
	public @ResponseBody String plateImageUpload(HttpServletRequest request, HttpServletResponse response,
			@RequestParam("plateId") String plateId, ModelMap model,HttpSession session) throws UnsupportedEncodingException {
		JSONObject json = new JSONObject();
		response.setContentType("text/html;charset=utf-8;");
		request.setCharacterEncoding("utf-8");
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		//计算该专场轮播图总数
		int count=fileMap.size();
		List<PlateImage> plateImageList = plateImageService.selectPlateImageList(Long.parseLong(plateId.trim()));
		if(plateImageList != null){
			count += plateImageList.size();
		}
		if(count > 5){
			try {
				json.put("data","专场轮播图上传总数超过5张限制");
				response.getWriter().print(json);
				return "-1";
			} catch (IOException e) {
				log.debug("", e);
				return "-1";
			}
		}
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			// 获取MulipartFile对象
			MultipartFile upfile = entity.getValue();
			PlateImage img = new PlateImage();
			img.setId(Long.parseLong(plateId.trim()));
			img.setGmtCreate(new Date());
			img.setGmtModified(new Date());
			String re = upLoad(img, request,session, plateId, "plates", upfile, model);
			if (!"success".equals(re)) {
				model.addAttribute("message", re);
				try {
					response.getWriter().write("false");
				} catch (IOException e) {
					log.debug("上传文件出错", e);
					return "-1";
				}
				return "-1";
			}
			response.setContentType("text/html;charset=UTF-8");
			try {
				response.getWriter().write("true");
			} catch (IOException e) {
				log.debug("上传文件出错", e);
				return "-1";
			}

		}
		return "0";
	}

	private void canUpload(PlateImage img, HttpServletRequest request,HttpSession session, String id, String filePath,
			MultipartFile upfile, ModelMap model) throws ServiceCodeException{

		model.addAttribute("id", id);
		filePath = filePath == null ? id : filePath;
		model.addAttribute("filePath", filePath);


		fileUploadUtil.uploadFile(img, upfile, filePath);
		try{
			PlateImage plateImage= new PlateImage();
			plateImage.setPlateId(Long.parseLong(id));
			plateImage.setBigImageUrl(img.getBigImageUrl());
			plateImage.setOriginalImageUrl(img.getOriginalImageUrl());
			plateImage.setSmallImageUrl(img.getSmallImageUrl());
			plateImageService.insertPlateImage(plateImage);
		}catch (Exception e) {
			throw new ServiceCodeException(EnumCommonCode.COMMON_BUSINESS_ERROR.getErrorNo(),
					EnumCommonCode.COMMON_BUSINESS_ERROR.getClass() + "，专场上传保存图片信息出错");
		}
		// 判断是否是压缩文件，如果是压缩文件则解压
//		String exts = originalFilename.substring(originalFilename.lastIndexOf(".") + 1, originalFilename.length());
		/*try {
			baseRedisDao.updateValueByKey("plate:plate_"+id+"_img", img, 60*60*2*1000);
		} catch (Exception e) {
			throw new ServiceCodeException(EnumCommonCode.COMMON_BUSINESS_ERROR.getErrorNo(),
					EnumCommonCode.COMMON_BUSINESS_ERROR.getClass() + "，板块上传保存图片信息出错");
		}*/
		model.addAttribute("fileName", upfile.getOriginalFilename());

		model.addAttribute("success", "上传成功！");
	}

	private String upLoad(PlateImage img, HttpServletRequest request,HttpSession session, String id, String filePath,
			MultipartFile upfile, ModelMap model) {
		String result = null;
		if (UploadUtil.ifFileSizePermitted(upfile, FileUploadUtil.MAX_IMAG_SIZE, FileUploadUtil.MAX_FILE_SIZE)) {
			canUpload(img, request,session, id, filePath, upfile, model);
			result = "success";
		} else {
			result = "图片大小不能超过" + FileUploadUtil.MAX_IMAG_SIZE / 1024 / 1024 + "M";
		}
		return result;
	}
	
	/**
	 * 修改参数验证
	 * @param info
	 */
	private void validateParam(Plate info) {
		if (StringUtils.isBlank(info.getPlateCode())) {
			throw new ServiceCodeException(EnumBusinessCode.BUSINESS_1000.getErrorNo(),
					EnumBusinessCode.BUSINESS_1000.getErrorInfo()+"，请输入专场编码");
		}
		if (!StringUtil.regexLetterNum(info.getPlateCode())) {
			throw new ServiceCodeException(EnumBusinessCode.BUSINESS_1000.getErrorNo(), 
					EnumBusinessCode.BUSINESS_1000.getErrorInfo()+"，专场编码不能包含特殊字符");
		}
		if (StringUtils.isBlank(info.getPlateName())) {
			throw new ServiceCodeException(EnumBusinessCode.BUSINESS_1000.getErrorNo(),
					EnumBusinessCode.BUSINESS_1000.getErrorInfo()+"，请输入专场名称");
		}
//			if (!StringUtil.regexChinessLetterNum(info.getPlateName())) {
//				throw new ServiceCodeException(EnumBusinessCode.BUSINESS_1000.getErrorNo(),
//						EnumBusinessCode.BUSINESS_1000.getErrorInfo()+"，专场名称不能包含特殊字符");
//			}
		if (null==info.getPlateSort()) {
			throw new ServiceCodeException(EnumBusinessCode.BUSINESS_1000.getErrorNo(),
					EnumBusinessCode.BUSINESS_1000.getErrorInfo()+"，请输入专场排序值");
		}
		/*if(!StringUtil.isNumeric(info.getPlateSort())) {
			throw new ServiceCodeException(EnumBusinessCode.BUSINESS_1000.getCode(),
					EnumBusinessCode.BUSINESS_1000.getMessage()+"，板块排序值，请填写整数");
		}*/
		/*if (StringUtils.isBlank(info.getPlateTopShow())) {
			throw new ServiceCodeException(EnumBusinessCode.BUSINESS_1000.getErrorNo(),
					EnumBusinessCode.BUSINESS_1000.getErrorInfo()+"，请选择是否展示在首页");
		}*/
		/*if (!info.getPlateTopShow().equals("Y")&&!info.getPlateTopShow().equals("N")) {
			throw new ServiceCodeException(EnumBusinessCode.BUSINESS_1000.getErrorNo(),
					EnumBusinessCode.BUSINESS_1000.getErrorInfo()+"，请选择是否展示在首页");
		}*/
//			if (!StringUtil.regexChinessLetterNum(info.getPlateName())) {
//				throw new ServiceCodeException(EnumBusinessCode.BUSINESS_1000.getErrorNo(),
//						EnumBusinessCode.BUSINESS_1000.getErrorInfo()+"，专场名称不能包含特殊字符");
//			}
		if (StringUtils.isBlank(info.getPlateDetail())) {
			throw new ServiceCodeException(EnumBusinessCode.BUSINESS_1000.getErrorNo(),
					EnumBusinessCode.BUSINESS_1000.getErrorInfo()+"，请输入专场描述");
		}
	}
	
	@RequestMapping("/plate/ajax/updateLogo.htm")
	public void updateLogo(ModelMap model,@RequestParam(value = "plateId", required = true) String plateId,@RequestParam("uploadFile")MultipartFile upfile,HttpServletResponse response) throws Exception{
		JSONObject json = new JSONObject();
		if (plateId != null) {
			Long id=Long.parseLong(plateId);
			Plate img = new Plate();
			img.setId(Long.parseLong(plateId.trim()));
			img.setGmtCreate(new Date());
			img.setGmtModified(new Date());
			fileUploadUtil.uploadFile(img, upfile, "plateLogo");
			baseRedisDao.updateValueByKey("plate:plate_"+id+"_img", img, 60*60*2*1000);
			json.put("data", img.getSmallImageUrl());
			
		}
		try {
			response.getWriter().print(json);
		} catch (Exception e) {
			log.error(e, e);
		}
	}
	
	@RequestMapping("/plate/ajax/plateInfo.json")
	@ResponseBody
	public JsonModel getPlateInfo(@RequestParam(value = "plateId") Long plateId){
	    PlateInfo plateInfo = plateService.selectPlateInfoById(plateId);
	    if (plateInfo == null) {
            return new JsonModel(JsonModel.RESULD_CODE_FAIL,"专场信息不存在");
        }
	    JsonModel result = new JsonModel();
	    FormInfo form = formFacadeService.getFormInfoByCode(PlateService.DYNAMIC_FORM_CODE);
	    if (form != null) {
            form.loadValues(plateInfo.getFormAttrValueList());
            Map<String,String> values = new HashMap<String, String>();
            values.put(EnumFormAttrMeta.DISCOUNT_RATES.getAttrKey(), form.getAttrValue(EnumFormAttrMeta.DISCOUNT_RATES.getAttrKey()));
            result.setData(values);
        }
	    return result;
	}

	@RequestMapping("/plate/getGoodsList.htm")
	public String getGoodsList(@ModelAttribute("query")GoodsQuery query){
		goodsService.queryGoodsPlateList(query);
		return "plate/goodsList";
	}
}
